package com.ykefu.assign.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author likai
 * @date 2020/4/6 17:45
 * @email likai@7moor..com
 * @desc
 */
public class DiscardClient {

    public static void main(String[] args) throws InterruptedException, IOException {
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(loopGroup);
        b.channel(NioSocketChannel.class);
        //b.option(ChannelOption.SO_KEEPALIVE,true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new DiscardClientHandler() );
            }
        });
        //start client
        ChannelFuture connect = b.connect("127.0.0.1", 8080);

        Channel channel = connect.sync().channel();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            System.out.println("client："+msg);
            if (msg == null) {
                break;
            } else {
                ChannelFuture channelFuture = channel.writeAndFlush(Unpooled.copiedBuffer(msg, Charset.forName("utf-8")));
                channelFuture.addListener((GenericFutureListener)(future)->{
                    boolean success = future.isSuccess();
                    Object now = future.getNow();
                    String s = future.toString();
                    System.out.println("success:"+success+",now:"+now+",s:"+s);
                });
            }
        }

//

        loopGroup.shutdownGracefully();

    }


}
